package com.shuai.api_platform.controller;

import com.shuai.api_platform.common.BaseResponse;
import com.shuai.api_platform.common.ErrorCode;
import com.shuai.api_platform.exception.BusinessException;
import com.shuai.api_platform.model.dto.*;
import com.shuai.api_platform.model.request.BussRequest;
import com.shuai.api_platform.model.request.SendEmailRequest;
import com.shuai.api_platform.model.request.WeatherQueryRequest;
import com.shuai.api_platform.model.vo.EmailSentVO;
import com.shuai.api_platform.model.vo.WeatherVO;
import com.shuai.api_platform.service.EmailService;
import com.shuai.api_platform.service.ThirdPlatformsService;
import com.shuai.api_platform.utils.EmailCodeUtils;
import com.shuai.api_platform.utils.ExcelReader;
import com.shuai.api_platform.utils.ResultUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.mail.MessagingException;

@RestController
@RequestMapping("/platform")
public class ThirdPlatformsController {

    @Autowired
    private ThirdPlatformsService thirdPlatformsService;

    @Autowired
    private EmailService emailService;

    /**
     * 查询天气信息的接口
     */
    @PostMapping("/weather")
    public BaseResponse<WeatherVO> getWeather(@RequestBody WeatherQueryRequest weatherQueryRequest) {
        String address = weatherQueryRequest.getAddress();
        String extensions = weatherQueryRequest.getExtensions();


        if (StringUtils.isBlank(address)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 获得二级区域对应编码
        String adcode = ExcelReader.dataMap.get(address);
        if (StringUtils.isBlank(adcode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "城市不存在或尚未开放查询！");
        }
        WeatherModel weatherModel;
        if (StringUtils.isNotBlank(extensions) && "all".equals(extensions)) {
            // 预测天气
            weatherModel = thirdPlatformsService.getWeatherInfoPredict(adcode);
        } else {
            // 实况天气
            weatherModel = thirdPlatformsService.getWeatherInfo(adcode);
        }
        if (!weatherModel.getInfocode().equals("10000")) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询当前城市天气信息失败");
        }
        WeatherVO weatherVO = new WeatherVO();
        if (weatherModel.getLives() != null && !weatherModel.getLives().isEmpty()) {
            LivesModel livesModel = weatherModel.getLives().get(0);
            BeanUtils.copyProperties(livesModel, weatherVO);
        } else {
            ForecastsModel forecastsModel = weatherModel.getForecasts().get(0);
            BeanUtils.copyProperties(forecastsModel, weatherVO);
        }
        return ResultUtils.success(weatherVO);
    }

    /**
     * 发送邮箱验证码的接口
     */
    @PostMapping("/email")
    public BaseResponse<EmailSentVO> sendEmail(@RequestBody SendEmailRequest sendEmailRequest) {
        if (sendEmailRequest == null || StringUtils.isAnyBlank(sendEmailRequest.getEmail(), sendEmailRequest.getTitle())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        if (!EmailCodeUtils.validateFormat(sendEmailRequest.getEmail())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱格式错误");
        }
        if (StringUtils.isBlank(sendEmailRequest.getPrompt())) {
            sendEmailRequest.setPrompt("您的验证码为：\n");
        }
        if (StringUtils.isBlank(sendEmailRequest.getWarning())) {
            sendEmailRequest.setWarning("\n请勿泄露验证码!\n");
        }
        try {
            String code = emailService.sendCodeToUser(sendEmailRequest);
            EmailSentVO emailSentVO = new EmailSentVO();
            emailSentVO.setSentCode(code);
            return ResultUtils.success(emailSentVO);
        } catch (MessagingException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "发送邮箱验证码失败，请稍后重试！");
        }
    }


    /**
     * 查询公交信息接口
     */
    @PostMapping("/buss")
    public BaseResponse<BusStop> queryBussInfo(@RequestBody BussRequest bussRequest) {
        if (StringUtils.isBlank(bussRequest.getId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请填写公交站ID");
        }
        BussModel bussModel = thirdPlatformsService.getBussInfo(bussRequest);
        if (bussModel == null ||
                !"10000".equals(bussModel.getInfocode()) ||
                bussModel.getBusstops() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询服务异常，请稍后重试");
        }
        if (bussModel.getBusstops().isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "查询结果为空，请检查公交站编码");
        }
        return ResultUtils.success(bussModel.getBusstops().get(0));
    }


}
